package priv.lhy.ecm.datadispose;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import priv.lhy.common.constants.RedisConstant;

import java.util.concurrent.TimeUnit;

/**
 * @author: lihy
 * date: 2019/7/29 15:55
 * description:
 */
public abstract class AbstractDispose implements IDispose {

    @Autowired
    private StringRedisTemplate redisTemplate;



    /**
     * 合法数据处理，由子类实现
     * @param message
     * @return
     */
    @Override
    public abstract String disposeLegalData(String[] message);

    @Override
    public String disposeIllegalData(String ip) {
        int errorCount = 0;
        if (redisTemplate.hasKey(RedisConstant.COLLECTOR_IP_ERROR_PREFIX + ":" + ip)) {
            errorCount = Integer.valueOf(redisTemplate.opsForValue().get(RedisConstant
                    .COLLECTOR_IP_ERROR_PREFIX + ":" + ip));
        }
        errorCount++;
        if (errorCount >= RedisConstant.COLLECTOR_IP_ERROR_TIME) {
            //达到重试次数，加入黑名单
            redisTemplate.opsForValue().set(RedisConstant
                    .COLLECTOR_IP_BLACK_PREFIX + ":" + ip, "1", RedisConstant
                    .COLLECTOR_BLACK_EXPIRE, TimeUnit.MINUTES);
        } else {
            //未达到重试次数，自增一
            redisTemplate.boundValueOps(RedisConstant.COLLECTOR_IP_ERROR_PREFIX + ":" + ip).increment(1);
            redisTemplate.expire(RedisConstant.COLLECTOR_IP_ERROR_PREFIX + ":" + ip,
                    RedisConstant.COLLECTOR_BLACK_EXPIRE, TimeUnit.MINUTES);
        }
        return "非法数据，还可重试" + (RedisConstant.COLLECTOR_IP_ERROR_TIME - errorCount) + "次";
    }
}
